#include "login.h"
#include "ui_login.h"

Login::Login(QWidget *parent)
    : QMainWindow(parent),
      ui(new Ui::Login)
{
    ui->setupUi(this);
    setWindowFlags(Qt::WindowCloseButtonHint);
    setWindowTitle("登录");
    setWindowOpacity(0.95);
    setFixedSize(this->width(), this->height());
    UIDesign::setButtonUI(ui->pushButton);
    UIDesign::setButtonUI(ui->regButton);
    UIDesign::setButtonUI(ui->changeCode);
    UIDesign::setButtonUI(ui->delButton);
    UIDesign::setLineEditUI(ui->userName);
    UIDesign::setLineEditUI(ui->password);
    UIDesign::setTransparent(ui->label);
    UIDesign::setTransparent(ui->label_2);
    UIDesign::setWindowUI(ui->centralwidget);

    sock = new QTcpSocket();
    sock->connectToHost("192.168.56.1", 8899);
    //sock->connectToHost("10.195.225.103", 8899);
    connect(sock, SIGNAL(connected()), this, SLOT(handConnected()));
}

Login::~Login()
{
    delete ui;
}

void Login::on_pushButton_clicked(){
    QString uName = ui->userName->text();
    QString pWord = ui->password->text();

    QJsonObject request;
    request.insert("order", 1);
    request.insert("myid", uName);
    QJsonObject data;
    data.insert("pwd", pWord);
    request.insert("data", data);
    qDebug() << request;
    QJsonDocument document;
    document.setObject(request);
    QByteArray byteRequest = document.toJson();
    sock->write(byteRequest);
}

void Login::handConnected(){
    ui->pushButton->setEnabled(true);
    connect(sock, SIGNAL(readyRead()), this, SLOT(handRead()));
}

void Login::handRead(){

    QByteArray byteRequest;
    byteRequest = sock->readAll();
    QJsonParseError err;
    QJsonDocument document = QJsonDocument::fromJson(byteRequest, &err);
    if(err.error == QJsonParseError::NoError)
    {
        QJsonObject request = document.object();
        QJsonValue Rstatus = request.value("status");
        bool status = Rstatus.toBool();
        if(status)
        {
            QMessageBox::information(this, "提示","登陆成功");
            MainWindow *mw = new MainWindow(sock, "0");
            mw->show();
            this->hide();
        }
        else
        {
            QMessageBox::warning(this, "警告", "密码错误！");
        }
    }
    else QMessageBox::warning(this, "警告", "服务器下传失败");

}
void Login::reStart()
{
    this->show();
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(sock, SIGNAL(readyRead()), this, SLOT(handRead()));
}

void Login::on_regButton_clicked()
{
    //打开注册界面
    regi *reg = new regi(sock, this);
    reg->show();
    this->hide();
    connect(reg, SIGNAL(mainclose()), this, SLOT(reStart()));
}

void Login::on_changeCode_clicked()
{
    //打开修改密码界面
    reCode * rec = new reCode(sock, this);
    rec->show();
    this->hide();
    connect(rec, SIGNAL(mainclose()), this, SLOT(reStart()));
}

void Login::on_delButton_clicked()
{
    Del * del = new Del(sock, this);
    del->show();
    this->hide();
    connect(del, SIGNAL(mainclose()), this, SLOT(reStart()));
}
